<?
// $Id: eBayTemplate.php,v 1.4 2008/08/17 05:23:42 kokbeng Exp $

/*
================ eBay Template API v1.0 ================
This class loads in the eBay Template from the
live template API, then caches it.

PRE-REQUISITES: PHP 5, mail, CURL,
chmod(755)ed caching directory.
========================================================
*/
class eBayTemplate{
	#The URL to the eBay Template API.
	private $api="http://tools.ebay.com.au/template/";

	#The directory to store all the cached files.
	public $cache_dir="/home/cmpl396/out/template-api/cache/";

	#The number of hours to cache a version of the template.
	public $caching=72;

	private $__cacher=NULL;

	#Constructor
	public function __construct(){
		$this->__cacher=new cacher();
	}

	#Load the template.
	public function load($params){
		$result=false;

		#Check the params are valid.
		if(substr($params,0,1)!="?"){
			$params="?$params";
		}

		#Check if we have a valid local version cached.
		$cached_file=@md5($params).".tpl"; #The Cached File Name.

		$last_modified=@filemtime($this->cache_dir.$cached_file); #Get the Date is was last modified.

		#Check if the file was created during the caching period.
		if($last_modified>time()-($this->caching*60*60)){
			#The cache file has been updated recently, so we'll load the template from there.
			$result=$this->loadCachedTemplate($cached_file);
		}else{
			#The cache either doesn't exist, or it's too old, so we'll use the Template API to load in the live template and create a cache of it.
			if($result=$this->loadApiTemplate($params)){
				#We now have an updated template, so lets cache it.
				$this->cacheTemplate($cached_file,$result);
			}else{
				#We've received an error, let's log it by emailing an eBay technical somebody.
				$this->logError("Failed to load in the API Template.");

				#Get the cache file that has been updated recently, so we'll load the template from there.
				$result=$this->loadCachedTemplate($cached_file);

				#Update the date modified on the cached file so we dont keep getting errors.
				@touch($this->cache_dir.$cached_file);
			}
		}
		//return($result);
		return($this->split($result));
	}

	#Read in the locally cached version of a template.
	private function loadCachedTemplate($cached_file){
		$result=false;
		$file=$this->cache_dir.$cached_file;
		if(@file_exists($file)){
			$result=@file_get_contents($file);
			if(!$result){
				$this->logError("file_get_contents($file) raised an error.");
			}
		}else{
			$this->logError("The caching file ($file) does not exist.");
		}
		return($result);
	}

	#Load in the template from the live API.
	private function loadApiTemplate($params){
		$url=$this->api.$params;
		$ch=curl_init();
		@curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		@curl_setopt($ch,CURLOPT_URL,$url);
		$result=curl_exec($ch);
		@curl_close($ch);
		if(strlen($result)<1){
			$result=false;
		}
		return($result);
	}

	#Cache the template we've received from the live API.
	private function cacheTemplate($file_name,$template_data){
		$file=$this->cache_dir.$file_name;
		if(!@file_put_contents($file,$template_data)){
			$this->logError("It was not possible to cache the template: check permissions or file name (fn=$file).");
		}
	}

	#Send an email to an eBay developer to look into why this error is occuring.
	private function logError($error){
		$error=date("d/m/Y H:i:s")." - ERROR{$error} - URL{".$this->getFullUrl()."}\n";
		@file_put_contents($this->cache_dir."error_log",$error,FILE_APPEND);
		$subject="ebayTemplate.php ERROR!!";
		//@mail("tgeiger@ebay.de",$subject,$error);
		//@mail("lsorhus@hotmail.com",$subject,$error);
		//@mail("pawood@ebay.com",$subject,$error);
		@mail("kokbeng@connectedmachines.com",$subject,$error);
		@mail("ebayau@connectedmachines.com",$subject,$error);
	}

	#Get the full current URL.
	private function getFullUrl(){
		$s=empty($_SERVER["HTTPS"])?'':($_SERVER["HTTPS"]=="on")?"s":"";
		$protocol=substr(strtolower($_SERVER["SERVER_PROTOCOL"]),0,strpos(strtolower($_SERVER["SERVER_PROTOCOL"]),"/")).$s;
		$port=($_SERVER["SERVER_PORT"]=="80")?"":(":".$_SERVER["SERVER_PORT"]);
		return($protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']);
	}

	public function split($content) {
		if( strlen($content) > 0 ) {
			$tmp_section = "";
			$regexp = "<!-- eBayTemplate::BP(::[^/]*)*//-->";
			if( eregi($regexp, $content) ) {
				$tmp_section = split($regexp, $content);
				//$htmlOpen  = $tmp_section[0];
				$htmlHead  = $tmp_section[1];
				//$htmlTags  = $tmp_section[2];
				$htmlBody  = $tmp_section[3];
				//$htmlBlank = $tmp_section[4];
				$htmlFoot  = $tmp_section[5];
				//$htmlClose = $tmp_section[6];
				$urlGetSuccess = true;

				$section = $_GET["section"];
				if($section == "head") {
					return $htmlHead;
				} elseif($section == "body") {
					return $htmlBody;
				} elseif($section == "foot") {
					return $htmlFoot;
				} else {
					return $content;
				}
			}
		}
	}

	public function loadNoCache($params) {
		if(substr($params,0,1)!="?"){
			$params="?$params";
		}
		if($result=$this->loadApiTemplate($params)) {
			return($this->split($result));
		}
	}
}
?>
